package com.mojavelinux.open18;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;

@Name( "courseFactory" )
public class CourseFactory {

	@In("#{golfRegulation}")
	private GolfRegulation regulation;
	
	public Course createCourse() {
		Course course = new Course();
		course = new Course();
		
		course.setType( CourseAccessType.PUBLIC );
		course.setGreens( GrassType.UNKNOWN );
		
		Address address = new Address();
		address.setCountry( "United States" );
		course.setAddress( address );

		TeeSet medal = new TeeSet();
		medal.setColor( "blue" );
		course.addTeeSet( medal );

		TeeSet normal = new TeeSet();
		normal.setColor( "white" );
		course.addTeeSet( normal );

		TeeSet ladies = new TeeSet();
		ladies.setColor( "red" );
		course.addTeeSet( ladies );

		return course;
	}
	
	/**
	 * Add 18 holes and (18 * number of tee sets) tees to a course.
	 */
	public void initializeScorecard( Course course ) {
		
		List<Hole> holes = new ArrayList<Hole>();
		for ( int holeNumber : regulation.getHoleNumbers() ) {
			Hole hole = createHole( holeNumber );
			course.addHole( hole );
			holes.add( hole );
		}
		
		if ( course.getTeeSets().size() == 0 ) {
			course.addTeeSet( new TeeSet( "blue" ) );
			course.addTeeSet( new TeeSet( "white" ) );
			course.addTeeSet( new TeeSet( "red" ) );
		}
		
		for ( TeeSet teeSet : course.getTeeSets() ) {
			for ( int holeNumber : regulation.getHoleNumbers() ) {
				teeSet.addTee( createTee( holes.get( holeNumber - 1 ) ) );
			}
		}
		
	}
	
	/**
	 * Since USGARating is an embeddable class, and Hibernate does not
	 * create an instance of an embedded reference if all fields are null,
	 * we need to create stub classes before going into the JSF form.
	 * Otherwise, JSF will freak when trying to set the property values
	 * because the parent component (in this case USGARating) will be null.
	 */
	public void initializeRatings( Set<TeeSet> teeSets ) {
		for ( TeeSet teeSet : teeSets ) {
			if ( teeSet.getMensRating() == null ) {
				teeSet.setMensRating( new USGARating() );
			}

			if ( teeSet.getLadiesRating() == null ) {
				teeSet.setLadiesRating( new USGARating() );
			}
		}
	}
	
	private Hole createHole( int number ) {
		return new Hole( number );
	}
	
	private Tee createTee( Hole hole ) {
		Tee tee = new Tee();
		tee.setHole( hole );
		return tee;
	}

}
